﻿#ifndef MEDIAPLAYER_H
#define MEDIAPLAYER_H

#include <QMutex>
#include <QObject>
#include <QSettings>
#include <QUdpSocket>
#include <QWaitCondition>

// extern "C" {
// struct AVFrame; // 仅声明
// struct AVCodecContext;
// struct AVSampleFormat;
// }
extern "C"{
#include <libavcodec/avcodec.h>
#include <libavfilter/avfilter.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
}

class MediaPlayer:public QObject
{
    Q_OBJECT
public:
    enum PLAYER_STATE{
        PLAYER_ERR = -1,
        PLAYER_START = 1,
        PLAYER_PAUSE,
        PLAYER_END,
    };
    enum CH_MODE{
        CH_STEREO = 1,
        CH_LEFT,
        CH_RIGHT
    };
    Q_ENUM(PLAYER_STATE)
    Q_ENUM(CH_MODE)

    MediaPlayer(QString taskId,int sessionId, QString device, int bitrate, CH_MODE chMode,bool useFFmpeg = false, QObject *parent = nullptr);
    ~MediaPlayer();
    void recordAudioFFmepg();
    void recordAudio();
    void start();
    void stop();
    void pause();
signals:
    void sigRecordFinished();
    void sigFinished();
    void playerStateChanged(PLAYER_STATE playerState,QString taskId,int sessionId,QString errMsg = "");
protected:
    static QString avErr2Str(int error);
    void writeFile(AVFrame *frame,FILE *file);
    int sendAudio(QUdpSocket &udpSocket, const uint8_t *data, size_t size,FILE *file = nullptr);
    void audioMix(QByteArray &ba, AVFrame *frame, CH_MODE chMode, int frame_size, int bytes_per_sample);
    QString getChModeStr(CH_MODE chMode);
private:
    QString _taskId;
    int _sessionId;
    QString _device;
    int _bitrate;
    CH_MODE _chMode;
    QThread *_workThread;
    QMutex _mutex;               // 用于保护共享变量
    QWaitCondition _condition;   // 用于线程间通知
    bool _isRunning;             // 线程是否运行
    bool _isPaused;              // 线程是否暂停
    QHostAddress _audioAddress;
    int _audioPort;
    int _frameIndex;
    int _sendInc;
    bool _saveRecord;
};
Q_DECLARE_METATYPE(MediaPlayer::PLAYER_STATE)
Q_DECLARE_METATYPE(MediaPlayer::CH_MODE)
#endif // MEDIAPLAYER_H
